import { View, Text, Image } from '@tarojs/components'
import { useState, useEffect } from 'react'
import { 
  Cell, 
  CellGroup, 
  Radio, 
  RadioGroup,
  Button,
  Card,
  Dialog,
  Toast,
  Avatar,
  Tag,
  Divider
} from '@nutui/nutui-react-taro'
import Taro, { useLoad, useRouter } from '@tarojs/taro'
import './index.less'

export default function Payment() {
  const router = useRouter()
  const [paymentMethod, setPaymentMethod] = useState('wechat')
  const [orderInfo, setOrderInfo] = useState(null)
  const [amount, setAmount] = useState(0)
  const [paymentType, setPaymentType] = useState('order') // order 或 member
  const [memberLevel, setMemberLevel] = useState('')
  const [userInfo, setUserInfo] = useState(null)
  const [showPayDialog, setShowPayDialog] = useState(false)
  const [paying, setPaying] = useState(false)

  const paymentMethods = [
    { 
      value: 'wechat', 
      label: '微信支付', 
      icon: 'https://img.yzcdn.cn/vant/wechat-pay.png',
      desc: '推荐使用微信支付',
      color: '#07c160',
      bgColor: '#f0f9ff'
    },
    { 
      value: 'alipay', 
      label: '支付宝', 
      icon: 'https://img.yzcdn.cn/vant/alipay.png',
      desc: '支持花呗分期',
      color: '#1677ff',
      bgColor: '#f6ffed'
    },
    { 
      value: 'unionpay', 
      label: '银联支付', 
      icon: 'https://img.yzcdn.cn/vant/unionpay.png',
      desc: '银行卡安全支付',
      color: '#eb2f96',
      bgColor: '#fff0f6'
    }
  ]

  useLoad(() => {
    const { orderId, amount: payAmount, type, level } = router.params
    
    setAmount(Number(payAmount) || 0)
    setPaymentType(type || 'order')
    setMemberLevel(level || '')
    
    // 获取用户信息
    try {
      const user = Taro.getStorageSync('userInfo')
      if (user) {
        setUserInfo(user)
      }
    } catch (error) {
      console.log('获取用户信息失败')
    }

    // 如果是订单支付，获取订单信息
    if (orderId && type !== 'member') {
      loadOrderInfo(orderId)
    }
  })

  const loadOrderInfo = (orderId) => {
    try {
      const orders = Taro.getStorageSync('orders') || []
      const order = orders.find(item => item.id === orderId)
      if (order) {
        setOrderInfo(order)
      }
    } catch (error) {
      Toast.show('获取订单信息失败')
    }
  }

  const calculateMemberDiscount = () => {
    if (userInfo?.isMember && paymentType === 'order') {
      return amount * 0.1 // 会员9折，节省10%
    }
    return 0
  }

  const getFinalAmount = () => {
    return amount - calculateMemberDiscount()
  }

  const handlePayment = () => {
    setShowPayDialog(true)
  }

  const confirmPayment = async () => {
    setPaying(true)
    setShowPayDialog(false)
    
    try {
      // 模拟支付过程
      await new Promise(resolve => setTimeout(resolve, 2000))
      
      if (paymentType === 'member') {
        // 开通会员
        const updatedUser = {
          ...userInfo,
          isMember: true,
          memberLevel: memberLevel,
          memberExpireDate: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toLocaleDateString()
        }
        Taro.setStorageSync('userInfo', updatedUser)
        Toast.show('会员开通成功！')
        
        setTimeout(() => {
          Taro.navigateBack()
        }, 1500)
      } else {
        // 订单支付
        if (orderInfo) {
          const orders = Taro.getStorageSync('orders') || []
          const updatedOrders = orders.map(order => 
            order.id === orderInfo.id 
              ? { ...order, status: 'picked', payTime: new Date().toLocaleString() }
              : order
          )
          Taro.setStorageSync('orders', updatedOrders)
        }
        
        Toast.show('支付成功！')
        setTimeout(() => {
          Taro.switchTab({ url: '/pages/orders/index' })
        }, 1500)
      }
    } catch (error) {
      Toast.show('支付失败，请重试')
    } finally {
      setPaying(false)
    }
  }

  const getPaymentTitle = () => {
    if (paymentType === 'member') {
      return `开通${memberLevel}`
    }
    return '订单支付'
  }

  return (
    <View className='payment-page'>
      {/* 顶部装饰背景 */}
      <View className='payment-header'>
        <View className='header-bg'>
          <View className='bg-circle circle-1'></View>
          <View className='bg-circle circle-2'></View>
          <View className='bg-circle circle-3'></View>
        </View>
        
        {/* 支付信息卡片 */}
        <View className='payment-info-card'>
          <View className='payment-icon'>
            {paymentType === 'member' ? '👑' : '💳'}
          </View>
          <Text className='payment-title'>{getPaymentTitle()}</Text>
          
          <View className='amount-section'>
            {calculateMemberDiscount() > 0 && (
              <View className='discount-info'>
                <Text className='original-price'>原价 ¥{amount}</Text>
                <Tag type='success' size='small'>会员9折</Tag>
              </View>
            )}
            <View className='final-amount-wrapper'>
              <Text className='currency-symbol'>¥</Text>
              <Text className='final-amount'>{getFinalAmount().toFixed(2)}</Text>
            </View>
            {calculateMemberDiscount() > 0 && (
              <Text className='save-amount'>已为您节省 ¥{calculateMemberDiscount().toFixed(2)}</Text>
            )}
          </View>
        </View>
      </View>

      {/* 订单详情 */}
      {orderInfo && (
        <View className='detail-section'>
          <View className='section-header'>
            <Text className='section-icon'>📋</Text>
            <Text className='section-title'>订单详情</Text>
          </View>
          <View className='detail-card'>
            <View className='detail-item'>
              <Text className='detail-label'>订单号</Text>
              <Text className='detail-value'>{orderInfo.id}</Text>
            </View>
            <Divider />
            <View className='detail-item'>
              <Text className='detail-label'>服务类型</Text>
              <View className='service-type'>
                <Text className='service-icon'>
                  {orderInfo.serviceType === 'wash' ? '🧺' : orderInfo.serviceType === 'dry-clean' ? '👔' : '🪡'}
                </Text>
                <Text className='detail-value'>
                  {orderInfo.serviceType === 'wash' ? '普通洗涤' : orderInfo.serviceType === 'dry-clean' ? '干洗' : '修补'}
                </Text>
              </View>
            </View>
            <Divider />
            <View className='detail-item'>
              <Text className='detail-label'>衣物数量</Text>
              <Text className='detail-value'>{orderInfo.clothesCount}件</Text>
            </View>
            <Divider />
            <View className='detail-item'>
              <Text className='detail-label'>服务地址</Text>
              <Text className='detail-value address'>{orderInfo.address}</Text>
            </View>
          </View>
        </View>
      )}

      {/* 会员信息 */}
      {paymentType === 'member' && (
        <View className='detail-section'>
          <View className='section-header'>
            <Text className='section-icon'>👑</Text>
            <Text className='section-title'>会员详情</Text>
          </View>
          <View className='member-card'>
            <View className='member-level'>
              <Avatar size='large' className='member-avatar'>
                👑
              </Avatar>
              <View className='member-info'>
                <Text className='member-title'>{memberLevel}</Text>
                <Text className='member-subtitle'>尊享会员特权</Text>
              </View>
            </View>
            <View className='member-benefits'>
              <View className='benefit-item'>
                <Text className='benefit-icon'>⏰</Text>
                <Text className='benefit-text'>有效期365天</Text>
              </View>
              <View className='benefit-item'>
                <Text className='benefit-icon'>💰</Text>
                <Text className='benefit-text'>享受9折优惠</Text>
              </View>
              <View className='benefit-item'>
                <Text className='benefit-icon'>🎁</Text>
                <Text className='benefit-text'>专属客服</Text>
              </View>
            </View>
          </View>
        </View>
      )}

      {/* 支付方式 */}
      <View className='payment-methods-section'>
        <View className='section-header'>
          <Text className='section-icon'>💳</Text>
          <Text className='section-title'>选择支付方式</Text>
        </View>
        
        <View className='payment-methods-card'>
          <RadioGroup value={paymentMethod} onChange={setPaymentMethod}>
            {paymentMethods.map(method => (
              <View 
                key={method.value}
                className={`payment-method-item ${paymentMethod === method.value ? 'active' : ''}`}
                onClick={() => setPaymentMethod(method.value)}
              >
                <View className='method-content'>
                  <View className='method-left'>
                    <View 
                      className='method-icon'
                      style={{ 
                        backgroundColor: method.bgColor,
                        color: method.color 
                      }}
                    >
                      <Image 
                        src={method.icon} 
                        style={{ width: '24px', height: '24px' }}
                        mode='aspectFit'
                      />
                    </View>
                    <View className='method-info'>
                      <Text className='method-name'>{method.label}</Text>
                      <Text className='method-desc'>{method.desc}</Text>
                    </View>
                  </View>
                  <View className='method-radio'>
                    <Radio value={method.value} />
                  </View>
                </View>
              </View>
            ))}
          </RadioGroup>
        </View>
      </View>

      {/* 安全提示 */}
      <View className='security-notice'>
        <View className='notice-content'>
          <Text className='notice-icon'>🔒</Text>
          <Text className='notice-text'>
            您的支付信息将通过SSL加密传输，确保交易安全。支持7天无理由退款。
          </Text>
        </View>
      </View>

      {/* 优惠信息 */}
      {userInfo?.isMember && paymentType === 'order' && (
        <View className='discount-notice'>
          <Text className='notice-text'>🎉 会员专享9折优惠已自动应用</Text>
        </View>
      )}

      {/* 支付按钮 */}
      <View className='payment-footer'>
        <View className='payment-summary'>
          <Text className='summary-text'>
            实付金额: <Text className='summary-amount'>¥{getFinalAmount().toFixed(2)}</Text>
          </Text>
        </View>
        <Button 
          type='primary' 
          size='large'
          loading={paying}
          onClick={handlePayment}
          className='pay-btn'
        >
          {paying ? '支付中...' : `确认支付 ¥${getFinalAmount().toFixed(2)}`}
        </Button>
      </View>

      {/* 支付确认对话框 */}
      <Dialog
        visible={showPayDialog}
        title='确认支付'
        content={`确认使用${paymentMethods.find(m => m.value === paymentMethod)?.label}支付 ¥${getFinalAmount().toFixed(2)} 吗？`}
        onCancel={() => setShowPayDialog(false)}
        onConfirm={confirmPayment}
      />
    </View>
  )
}